//
//  DownLoad.m
//  Leisure
//
//  Created by lanou3g on 16/4/12.
//  Copyright © 2016年 wenze. All rights reserved.
//

#import "DownLoad.h"

@interface DownLoad ()<NSURLSessionDownloadDelegate>

@property (nonatomic,strong)NSURLSession *session;

@property (nonatomic,strong)NSURLSessionDownloadTask *task;
// 记录当前已经下载的数据
@property (nonatomic,strong)NSMutableData *data;

@end

@implementation DownLoad

- (instancetype)initWithUrl:(NSString *)url{
    if (self = [super init]) {
        // 创建config
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        // 创建session
        self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
        // 创建下载任务
        self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:url]];
        _url = url;
    }
    return self;
}

- (void)start{
    if (self.data) {
        self.task = [self.session downloadTaskWithResumeData:_data];
        
    }else{
        self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:self.url]];
    }
    [self.task resume];
    
    
}

- (void)pause{
    if (self.data) {
        [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
            self.data = [resumeData mutableCopy];
            self.task = nil;
        }];
    }else{
        NSLog(@"当前任务没有在下载");
    }
}

#pragma - mark ------DownLoadDelegate
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
    // 结束
    // 1.通知delegate 结束
    if ([_delegate respondsToSelector:@selector(didFinishLoadWithUrl:)]) {
        [self.delegate didFinishLoadWithUrl:self.url];
    }
    // 2. 把当前在临时目录下的文件移动到caches目录
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    // 获取下载任务反馈的服务器建议名称
    NSString *filePath = [caches stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
    // 移动文件
    NSFileManager *manager = [NSFileManager defaultManager];
    // location是url类型 location.path获取路径的字符串
    [manager moveItemAtPath:location.path toPath:filePath error:nil];
    // 参数是url类型
//    [manager moveItemAtURL:<#(nonnull NSURL *)#> toURL:<#(nonnull NSURL *)#> error:<#(NSError * _Nullable __autoreleasing * _Nullable)#>]
    // 3.需要保存当前的文件路径
    if (self.finishLoad) {
        self.finishLoad(filePath,self.url);
    }else{
        NSLog(@"需要实现- didFinishWithFinishLoad: andDownloading:");
    }
    
}


- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    // 下载速度  已经下载的内容   预计下载总量
    float progressValue = (float)totalBytesWritten/totalBytesExpectedToWrite;
    self.progress = progressValue * 100;
    if (self.downloading) {
        self.downloading(self.progress,bytesWritten);
    }else{
        NSLog(@"需要实现- didFinishWithFinishLoad: andDownloading:");
    }
}
// 给block赋值
- (void)didFinishWithFinishLoad:(FinishLoad)finish andDownloading:(Downloading)download{
    self.finishLoad = finish;
    self.downloading = download;
}









@end
